package com.automannn.websoketmqtt.consumer.config;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author chenkh
 * @time 2020/10/13 13:42
 */
@Component
public class AutomannnAckReceiver implements ChannelAwareMessageListener {

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            String msg = message.toString();
            String[] msgArray = msg.split("'");
            Map<String,String> msgMap = mapStringToMap(msgArray[1].trim(),3);
            String messageId = msgMap.get("messageId");
            String messageData = msgMap.get("messageData");
            String createTime = msgMap.get("createTime");
            System.out.println("AutomannnReceiver messageId:"+messageId+" messageData:"+messageData+" createTime:"+createTime);
            System.out.println("消费的主体消息来自: "+ message.getMessageProperties().getConsumerQueue());

            channel.basicAck(deliveryTag,true);
//            channel.basicReject(deliveryTag,true);
//            channel.basicNack(deliveryTag,true);
        }catch (Exception e){
            channel.basicReject(deliveryTag,false);
            e.printStackTrace();
        }
    }

    //{key=value,key=falue} 转为Map
    private Map<String, String> mapStringToMap(String str, int entryNum) {
        str = str.substring(1,str.length()-1);
        String[] strs = str.split(",",entryNum);
        Map<String,String> map = new HashMap<>();
        Arrays.asList(strs).forEach(item->{
            String key = item.split("=")[0].trim();
            String value =  item.split("=")[1];
            map.put(key,value);
        });
        return map;
    }
}
